package cn.acmenms.service.impl;

import cn.acmenms.exception.BusinessException;
import cn.acmenms.mapper.UserMapper;
import cn.acmenms.po.config.ConfigInfo;
import cn.acmenms.po.model.User;
import cn.acmenms.po.query.UserQuery;
import cn.acmenms.service.UserService;
import cn.acmenms.utils.Constants;
import cn.acmenms.utils.LocalDateTimeUtils;
import cn.acmenms.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Description: 用户业务实现
 * @author: 神奇的鸭鸭
 * @Date: 2017/12/28 13:26
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper<User, UserQuery> userMapper;

    public void register(User user) throws BusinessException {
        // 校验邮箱，用户名，密码是否合法
        String userName = user.getUserName();
        String email = user.getEmail();
        String password = user.getPassword();
        // 前端防君子不防小人
        if(StringTools.isEmpty(userName) || StringTools.isEmpty(email) || StringTools.isEmpty(password)
                || userName.length() > Constants.LENGTH_20
                || password.length() > Constants.LENGTH_16 || password.length() < Constants.LENGTH_6
                || !StringTools.checkEmail(email) || !StringTools.checkUserName(userName) || !StringTools.checkPassword(password)){
            logger.error("有人绕过前台攻击网站...", user);
            throw new BusinessException("输入参数不合法！请勿搞事");
        }
        // 校验用户是否已经存在
        if(this.findUserByUserName(user.getUserName()) != null) {
            throw new BusinessException("用户已存在");
        }
        // 校验邮箱是否已经存在
        if(this.findUserByEmail(user.getEmail()) != null) {
            throw new BusinessException("邮箱已经存在");
        }
        // 初始化时间
        LocalDateTime now = LocalDateTime.now();
        user.setRegisterTime(now);
        user.setLastLoginTime(now);
        // 初始化图片路径
        user.setUserIcon(Constants.USER_IMG_PATH_USER_ICON + ((int) (Math.random() * 10) + 1) + ".png");
        user.setUserBg(Constants.USER_IMG_PATH_USER_BG + ((int) (Math.random() * 10) + 1) + ".jpg");
        // 密码加密
        user.setPassword(StringTools.encodeByMD5(user.getPassword()));
        // 写库
        this.userMapper.insert(user);
    }

    public User findUserByUserName(String userName) {
        UserQuery query = new UserQuery();
        query.setUserName(userName);
        List<User> userList = userMapper.selectList(query);
        if (userList.size() == 1) {
            return userList.get(0);
        }
        return null;
    }

    public User findUserByEmail(String email) {
        UserQuery query = new UserQuery();
        query.setEmail(email);
        List<User> userList = userMapper.selectList(query);
        if (userList.size() == 1) {
            return userList.get(0);
        }
        return null;
    }

    public User login(String nameOrEmail, String password, Boolean encodePwd, String lastLoginIp) throws BusinessException {
        if(StringTools.isEmpty(nameOrEmail) || StringTools.isEmpty(password)){
            throw new BusinessException("这样的参数是不合法的... /(ㄒoㄒ)/~~求大仙放过小站");
        }
        User user;
        if(nameOrEmail.contains("@")){
            user = this.findUserByEmail(nameOrEmail);
        } else {
            user = this.findUserByUserName(nameOrEmail);
        }
        if(null == user){
            throw new BusinessException("用户不存在");
        }
        if(encodePwd){
            password = StringTools.encodeByMD5(password);
        }
        if(!user.getPassword().equals(password)){
            throw new BusinessException("密码错误");
        }
        // 更新最后登录信息
        this.updateLastLoginInfo(user.getUserId(), lastLoginIp, null);
        return user;
    }

    public void updateLastLoginInfo(Integer userId, String lastLoginIp, String ipAddress) {
        User newUser = new User();
        newUser.setUserId(userId);
        newUser.setLastLoginIp(lastLoginIp);
        newUser.setIpAddress(ipAddress);
        newUser.setLastLoginTime(LocalDateTime.now());
        userMapper.update(newUser);
    }

    public void sendCheckCode(String email, String checkCode) throws BusinessException {

    }

    public void resetPwd(String email, String password, String checkCode) throws BusinessException {

    }

    public void changeMark(Integer userId, int mark) {

    }

    public List<User> findAllActiveUser() {
        return null;
    }
}